package com.kaba.security.handler;

import com.alibaba.fastjson.JSON;
import com.kaba.bean.*;
import com.kaba.util.JwtUtil;
import com.kaba.xtzhgl.service.SysMenuService;
import com.kaba.xtzhgl.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lvmengjie
 * @Date 2021/3/22
 * @Description 登录成功
 */
@Component
public class LonginsuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysMenuService sysMenuService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //查出用户信息
        SysUser sysUser = sysUserService.queryByName(userDetails.getUsername());
        //根据用户名和密码生成token
        String token=JwtUtil.generateToken(sysUser.getUserName(),sysUser.getPassword());
        //查出用户对应的权限
        List<SysMenu> menus =sysMenuService.queryByname(sysUser.getUserId());
        //测试权限集合
        //List<SysMenu> menulist=sysMenuService.queryMenu();
        //将token和用户对应的权限吗装入map中返回前端
        Map<String ,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("menus",menus);
        //map.put("menulist",menulist);
        ResponseResult resulta=ResponseResult.success(ResultCode.SUCCESS,map);
        //返回json数据
        response.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        response.getWriter().write(JSON.toJSONString(resulta));

    }


}
